<template>
  <div>
    <el-drawer
      title="我是里面的"
      :append-to-body="true"
      :before-close="closeDrawer"
      :visible.sync="showAttendanceInfoStatus"
      :with-header="false"
      size="60%"
    >
      <div class="attendance-message-all-infomation">
        <!-- 表格内容 -->
        <p class="attendance-message-title">考勤名单</p>
        <!-- 表单全部信息 -->
        <div class="attendance-message-all-info">
          <el-collapse v-model="showUserScore" accordion>
            <el-collapse-item :title="`已签到人数：${isSign}人`" name="1">
              <el-table
                ref="attendanceTable"
                v-loading="loading"
                :data="attendanceMessageAllInfo.filter((value,index) => value.status ===true).slice((currentPage-1)*pagesize,currentPage*pagesize)"
                stripe
                fit
                highlight-current-row
                class="attendance-all-info"
                @selection-change="selectCheckUser"
              >
                <el-table-column
                  type="selection"
                  min-width="8%"
                />
                <el-table-column
                  label="序号"
                  type="index"
                  min-width="8%"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="checkUserId"
                  label="工号"
                  sortable
                  min-width="15%"
                />
                <el-table-column
                  align="center"
                  prop="checkUserName"
                  label="姓名"
                  sortable
                  min-width="12%"
                />
                <el-table-column
                  align="center"
                  prop="checkUserBranch"
                  label="所属党支部"
                  :filters="allBranch.map((item, index, arr) => {
                    const returnObj = { text: item.branchName, value: item.branchName }
                    return returnObj
                  })"
                  :filter-method="filterCheckTypeName"
                  min-width="15%"
                />
                <el-table-column
                  align="center"
                  prop="checkTypeName"
                  label="评分类型"
                  :filters="checkType.map((item, index, arr) => {
                    const returnObj = { text: item.checkName, value: item.checkName }
                    return returnObj
                  })"
                  :filter-method="filterCheckTypeName"
                  min-width="13%"
                />
                <el-table-column
                  align="center"
                  prop="checkScore"
                  label="得分"
                  sortable
                  min-width="10%"
                />
                <el-table-column
                  align="center"
                  prop="checkCreateTime"
                  label="签到时间"
                  sortable
                  min-width="15%"
                />
              </el-table>
              <el-row>
                <el-col :span="12" class="drop-info">
                  <el-button type="primary" @click="selectMessage(1)">更新</el-button>
                  <el-button type="danger" @click="selectMessage(3)">删除</el-button>
                </el-col>
                <el-col :span="12">
                  <!-- 分页功能 -->
                  <div id="pages" class="paging-info">
                    <el-pagination
                      :current-page="currentPage"
                      :page-sizes="[5,10,15,20,30,50]"
                      :page-size="pagesize"
                      layout="total , sizes , prev , pager , next"
                      :total="attendanceMessageAllInfo.filter((value,index) => value.status ===true).length"
                      prev-text="上一页"
                      next-text="下一页"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </el-col>
              </el-row>

            </el-collapse-item>
            <el-collapse-item :title="`未签到人数：${noSign}人`" name="2">
              <el-table
                ref="attendanceTable"
                v-loading="loading"
                :data="attendanceMessageAllInfo.filter((value,index) => value.status ===false).slice((noCurrentPage-1)*noPagesize,noCurrentPage*noPagesize)"
                stripe
                fit
                highlight-current-row
                class="attendance-all-info"
                @selection-change="selectChecknoUser"
              >
                <el-table-column
                  type="selection"
                  min-width="8%"
                />
                <el-table-column
                  label="序号"
                  type="index"
                  min-width="10%"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span>{{ (noCurrentPage - 1) * noPagesize + scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="checkUserId"
                  sortable
                  label="工号"
                  min-width="15%"
                />
                <el-table-column
                  align="center"
                  prop="checkUserName"
                  sortable
                  label="姓名"
                  min-width="12%"
                />
                <el-table-column
                  align="center"
                  prop="checkUserBranch"
                  :filters="allBranch.map((item, index, arr) => {
                    const returnObj = { text: item.branchName, value: item.branchName }
                    return returnObj
                  })"
                  :filter-method="filterCheckTypeName"
                  label="所属党支部"
                  min-width="15%"
                />
              </el-table>
              <!-- 分页功能 -->
              <el-row>
                <el-col :span="12" class="drop-info">
                  <el-button type="primary" @click="selectMessage(2)">更新</el-button>
                </el-col>
                <el-col :span="12">
                  <div id="pages" class="paging-info">
                    <el-pagination
                      :current-page="noCurrentPage"
                      :page-sizes="[5,10,15,20,30,50]"
                      :page-size="noPagesize"
                      layout="total , sizes , prev , pager , next"
                      :total="attendanceMessageAllInfo.filter((value,index) => value.status ===false).length"
                      prev-text="上一页"
                      next-text="下一页"
                      @size-change="noHandleSizeChange"
                      @current-change="noHandleCurrentChange"
                    />
                  </div>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </el-drawer>
    <!-- 更新签到信息弹出框 -->
    <el-dialog
      title="请选择签到类型"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-select v-model="inputDialog" placeholder="请选择">
          <el-option
            v-for="item in checkType"
            :key="item.checkName"
            :label="item.checkName"
            :value="[item.checkTypeId,item.checkTypeScore]"
          />
        </el-select>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary" @click="sendInputDialog()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="删除签到信息"
      :visible.sync="isShowDelUserSign"
      width="40%"
      :before-close="handleDelClose"
    >
      <p class="del-user-sign">您共删除数据{{ sendSign.length }}条签到信息。删除的人员为：<br>{{ sendSign.map((item)=>item.checkUserName).toString() }}。<br>点击确定后删除</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDelClose()">取 消</el-button>
        <el-button type="primary" @click="sendInputDialog()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getAddSend, getUpdateSendScore } from '@/api/send.js'
import { getGroups } from '../../api/branch.js'
import { getAttendanceByCheckId, addessay, updateMessage, deletecheckMessage } from '../../api/checkMessage.js'
import { getCheckTypeByCheckId } from '../../api/checkType.js'
import { getAllUserInfo } from '../../api/user.js'
// import { deepClone } from '../../utils/deepClone.js'
export default {
  data() {
    return {
      // 后台逻辑数据
      attendanceMessageAllInfo: [], // 考勤用户信息
      userAllInfo: [], // 用户全部信息
      checkType: [], // 考核类型全部信息
      attendStatus: 1, // 当前考勤状态 0 未开始 1 正在签到 2 已经结束 3 特殊问题
      checkId: '', // 考勤信息编号
      allBranch: [], // 所有党小组信息
      selectIsSign: [], // 选择签到信息数据
      selectNoSign: [], // 选择未签到信息数据
      dialogType: 0, // 管理类型
      inputDialog: [], // 选择的类型
      sendInfo: [], // sendInfo信息
      sendSign: [], // 需要更新的签到信息
      routerInfo: {}, // 路由信息
      // 页面存储数据
      showAttendanceInfoStatus: false, // 内层抽屉
      dialogVisible: false, // 展示签到信息弹出框
      isShowDelUserSign: false, // 删除信息弹出框
      showUserScore: ['1'], // 展示用户成绩表单
      isSign: 0, // 签到人数
      noSign: 0, // 未签到人数
      loading: true, // 展示页面详细数据
      currentPage: 1, // 默认显示页面为1
      pagesize: 10, // 每页的数据条数
      noCurrentPage: 1, // 默认显示页面为1
      noPagesize: 10 // 每页的数据条数
    }
  },
  created() {

  },
  methods: {
    // 获取考勤用户信息
    showDrawer(checkId, attendStatus, sendInfo, routerInfo) {
      var that = this
      this.showAttendanceInfoStatus = true
      that.sendInfo = sendInfo
      that.checkId = checkId
      that.attendStatus = attendStatus
      that.routerInfo = routerInfo
      // 获取所有党小组的名称和信息
      getGroups().then((res) => { that.allBranch = res.obj })
      // 根据考核id获取考勤类型信息
      getCheckTypeByCheckId(checkId).then((data) => {
        that.checkType = data.obj
        // 获取用户信息
        getAllUserInfo().then((res) => {
        // 根据考勤编号获取用户信息
          that.getAttendanceMessageInfo(checkId, res.obj, data.obj)
        })
      })
    },
    // 根据考勤编号获取用户信息
    getAttendanceMessageInfo(checkId, userAllInfo, checkType) {
      var that = this
      // 根据考勤编号获取用户信息
      getAttendanceByCheckId(checkId).then((res) => {
        that.attendanceMessageInfo = res.obj
        // 判断用户是否签到
        that.isUserQrcode(userAllInfo, res.obj, checkType)
      })
    },
    // 判断用户是否签到
    isUserQrcode(userAllInfo, attendanceMessageAllInfo, checkType) {
      var that = this
      const attendanceInfo = []
      for (const i in userAllInfo) {
        let isUser = false
        for (const j in attendanceMessageAllInfo) {
          if (userAllInfo[i].userId === attendanceMessageAllInfo[j].checkUserId) {
            isUser = true
            attendanceMessageAllInfo[j].status = true
            for (const t in checkType) {
              if (checkType[t].checkTypeId === attendanceMessageAllInfo[j].checkType) {
                attendanceMessageAllInfo[j].checkUserBranch = userAllInfo[i].userinfo.branch.branchName
                attendanceMessageAllInfo[j].checkTypeName = checkType[t].checkName
                break
              }
            }
            attendanceInfo.push(attendanceMessageAllInfo[j])
            break
          }
        }
        if (isUser === false) {
          // 用户未签到
          const attendanceBaseInfo = {
            checkAttendanceId: that.checkId,
            checkUserId: userAllInfo[i].userId,
            checkUserName: userAllInfo[i].userinfo.userName,
            checkUserBranch: userAllInfo[i].userinfo.branch.branchName,
            checkType: '',
            checkTypeName: '',
            checkScore: null,
            status: false
          }
          attendanceInfo.push(attendanceBaseInfo)
        }
      }
      let isSign = 0
      let noSign = 0
      attendanceInfo.forEach((item) => {
        if (item.status === true) {
          isSign++
        } else {
          noSign++
        }
      })
      that.attendanceMessageAllInfo = attendanceInfo
      that.isSign = isSign
      that.noSign = noSign
      that.loading = false
    },
    selectMessage(type) {
      var that = this
      if (type === 1 && that.selectIsSign.length === 0) {
        that.$message({
          message: '请选择后再操作',
          type: 'warning'
        })
      } else if (type === 2 && that.selectNoSign.length === 0) {
        that.$message({
          message: '请选择后再操作',
          type: 'warning'
        })
      } else if (type === 3 && that.selectIsSign.length === 0) {
        that.$message({
          message: '请选择后再操作',
          type: 'warning'
        })
      } else {
        if (type === 3) {
          that.sendSign = that.selectIsSign
          that.isShowDelUserSign = true
        } else {
          if (type === 1) {
            that.sendSign = that.selectIsSign
          } else if (type === 2) {
            that.sendSign = that.selectNoSign
          }
          that.dialogVisible = true
        }
        that.dialogType = type
      }
    },

    sendInputDialog() {
      const sendInfo = this.sendInfo
      const dialogType = this.dialogType
      var that = this
      const sendUser = this.sendSign
      if (dialogType !== 3 && (that.inputDialog === '' || that.inputDialog.length === 0 || that.inputDialog === undefined)) {
        that.$message({
          message: '请选择评分类型',
          type: 'warning'
        })
      } else {
        that.$message({
          message: '正在提交中',
          type: 'info'
        })
        if (dialogType === 1) {
          // update
          for (let i = 0; i < sendUser.length; i++) {
            const checkOldScore = sendUser[i].checkScore
            for (let j = 0; j < sendInfo.length; j++) {
              if (sendUser[i].checkUserId === sendInfo[j].userId) {
                let sendScore = sendInfo[j].send.sendScore - checkOldScore + that.inputDialog[1]
                if (sendScore > that.routerInfo.routerMaxScore) {
                  sendScore = that.routerInfo.routerMaxScore
                }
                if (sendScore < that.routerInfo.routerMinScore) {
                  sendScore = that.routerInfo.routerMinScore
                }
                const send = {
                  sendId: sendInfo[j].send.sendId,
                  sendUserId: sendUser[i].checkUserId,
                  sendFlistId: sessionStorage.getItem('flist'),
                  sendSlistId: sessionStorage.getItem('slist'),
                  sendTlistId: sessionStorage.getItem('tlist'),
                  sendSemseterId: sessionStorage.getItem('semId'),
                  sendGiveUserId: sessionStorage.getItem('userId'),
                  sendStatus: 1,
                  sendScore: sendScore
                }
                getUpdateSendScore(send, send.sendScore).then((res) => {
                  sendUser[i].checkScore = that.inputDialog[1]
                  sendUser[i].checkType = that.inputDialog[0]
                  updateMessage(sendUser[i]).then((res) => {
                    sendInfo[j].send.sendScore = send.sendScore
                    if (i === sendUser.length - 1) {
                      that.$message({
                        message: '提交成功',
                        type: 'success'
                      })
                      that.dialogVisible = false
                      that.inputDialog = ''
                      that.showDrawer(this.checkId, this.attendStatus, sendInfo, that.routerInfo)
                    }
                  })
                })
                break
              }
            }
          }
        } else if (dialogType === 2) {
          // add
          for (let i = 0; i < sendUser.length; i++) {
            const sendCheck = {
              checkAttendanceId: sendUser[i].checkAttendanceId,
              checkScore: that.inputDialog[1],
              checkType: that.inputDialog[0],
              checkUserId: sendUser[i].checkUserId,
              checkUserName: sendUser[i].checkUserName
            }
            // 判断是否首次添加
            for (let j = 0; j < sendInfo.length; j++) {
              if (sendUser[i].checkUserId === sendInfo[j].userId) {
                if (sendInfo[j].send.sendId === null) {
                  // 添加sendInfo信息
                  const send = {
                    sendUserId: sendUser[i].checkUserId,
                    sendFlistId: sessionStorage.getItem('flist'),
                    sendSlistId: sessionStorage.getItem('slist'),
                    sendTlistId: sessionStorage.getItem('tlist'),
                    sendSemseterId: sessionStorage.getItem('semId'),
                    sendGiveUserId: sessionStorage.getItem('userId'),
                    sendStatus: 1,
                    sendScore: that.inputDialog[1]
                  }
                  getAddSend(send).then((res) => {
                    addessay(sendCheck).then((data) => {
                      sendInfo[j].send.sendScore = send.sendScore
                      sendInfo[j].send.sendId = res.msg.split(' ')[1]
                      if (i === sendUser.length - 1) {
                        that.$message({
                          message: '提交成功',
                          type: 'success'
                        })
                        that.dialogVisible = false
                        that.inputDialog = ''
                        that.showDrawer(this.checkId, this.attendStatus, sendInfo, that.routerInfo)
                      }
                    })
                  })
                } else {
                  let sendScore = sendInfo[j].send.sendScore + that.inputDialog[1]
                  if (sendScore > that.routerInfo.routerMaxScore) {
                    sendScore = that.routerInfo.routerMaxScore
                  }
                  if (sendScore < that.routerInfo.routerMinScore) {
                    sendScore = that.routerInfo.routerMinScore
                  }
                  const send = {
                    sendId: sendInfo[j].send.sendId,
                    sendUserId: sendUser[i].checkUserId,
                    sendFlistId: sessionStorage.getItem('flist'),
                    sendSlistId: sessionStorage.getItem('slist'),
                    sendTlistId: sessionStorage.getItem('tlist'),
                    sendSemseterId: sessionStorage.getItem('semId'),
                    sendGiveUserId: sessionStorage.getItem('userId'),
                    sendStatus: 1,
                    sendScore: sendScore
                  }
                  getUpdateSendScore(send, send.sendScore).then((res) => {
                    addessay(sendCheck).then((res) => {
                      sendInfo[j].send.sendScore = send.sendScore
                      if (i === sendUser.length - 1) {
                        that.$message({
                          message: '提交成功',
                          type: 'success'
                        })
                        that.dialogVisible = false
                        that.inputDialog = ''
                        that.showDrawer(this.checkId, this.attendStatus, sendInfo, that.routerInfo)
                      }
                    })
                  })
                }
                break
              }
            }
          }
        } else if (dialogType === 3) {
          const checkType = that.checkType
          // del
          for (let i = 0; i < sendUser.length; i++) {
            for (let j = 0; j < sendInfo.length; j++) {
              if (sendUser[i].checkUserId === sendInfo[j].userId) {
                let sendScore = parseFloat(sendInfo[j].send.sendScore) - parseFloat(checkType.find((item) => item.checkTypeId === sendUser[i].checkType).checkTypeScore)
                if (sendScore > that.routerInfo.routerMaxScore) {
                  sendScore = that.routerInfo.routerMaxScore
                }
                if (sendScore < that.routerInfo.routerMinScore) {
                  sendScore = that.routerInfo.routerMinScore
                }
                const send = {
                  sendId: sendInfo[j].send.sendId,
                  sendUserId: sendUser[i].checkUserId,
                  sendFlistId: sessionStorage.getItem('flist'),
                  sendSlistId: sessionStorage.getItem('slist'),
                  sendTlistId: sessionStorage.getItem('tlist'),
                  sendSemseterId: sessionStorage.getItem('semId'),
                  sendGiveUserId: sessionStorage.getItem('userId'),
                  sendStatus: 1,
                  sendScore: sendScore
                }
                getUpdateSendScore(send, send.sendScore).then((res) => {
                  deletecheckMessage(sendUser[i].checkMessageId).then((res) => {
                    sendInfo[j].send.sendScore = send.sendScore
                    if (i === sendUser.length - 1) {
                      that.$message({
                        message: '删除成功',
                        type: 'success'
                      })
                      that.isShowDelUserSign = false
                      that.inputDialog = ''
                      that.showDrawer(this.checkId, this.attendStatus, sendInfo, that.routerInfo)
                    }
                  })
                })
                break
              }
            }
          }
        }
      }
    },
    // 页面逻辑方法
    // 筛选签到类型
    filterCheckTypeName(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    // 选择筛选人数
    selectCheckUser(val) {
      this.selectIsSign = val
    },
    selectChecknoUser(val) {
      this.selectNoSign = val
    },
    // 关闭dialog
    closeDrawer() {
      this.$confirm('是否确定关闭', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showAttendanceInfoStatus = false
      }).catch(() => {})
    },
    // 分页
    handleSizeChange(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    // 分页
    noHandleSizeChange(size) {
      this.noPagesize = size
    },
    // 点击第几页
    noHandleCurrentChange(currentPage) {
      this.noCurrentPage = currentPage
    },
    handleClose(done) {
      this.$confirm('是否关闭')
        .then(_ => {
          this.dialogVisible = false
          this.inputDialog = ''
        })
        .catch(_ => {})
    },
    handleDelClose(done) {
      this.isShowDelUserSign = false
      this.inputDialog = ''
    }
  }
}
</script>
<style>
  .el-drawer__body {
    overflow: auto;
    /* overflow-x: auto; */
}
</style>
<style lang="scss" scoped>
.attendance-message-all-infomation{
    width: 96%;
    margin:0 auto;
}
.attendance-message-title{
    margin-top: 3rem;
}
.drop-info{
    margin-top: 2rem;
}
.paging-info{
    margin-top: 2rem;
    margin-bottom: 1rem;
}
.attendance-all-info{
    height: 100%;
}
.del-user-sign{
  font-size: 0.9rem;
  line-height: 1.5;
}
</style>
